package com.hqins.app.cloud.common;


import org.springframework.boot.autoconfigure.web.ErrorAttributes;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
public class GenericErrorController implements ErrorController {
    @Resource
    ResponseObject baseValueObject;

    @Resource
    ErrorAttributes errorAttributes;


 /* @RequestMapping(produces = "text/html")
  public ModelAndView errorHtml(HttpServletRequest request,
                                HttpServletResponse response) {
    HttpStatus status = getStatus(request);
    response.setStatus(status.value());
    RequestAttributes requestAttributes = new ServletRequestAttributes(request);
    Map<String, Object> errorMap = this.errorAttributes.getErrorAttributes(requestAttributes, false);
    response.setHeader("error", errorMap.get("error") + " - " + errorMap.get("message"));
    response.setStatus(status.value());
    return  new ModelAndView("error", errorMap);
  }*/

    @RequestMapping
    @ResponseBody
    public Object error(HttpServletRequest request, HttpServletResponse response) {
        HttpStatus status = getStatus(request);
        response.setStatus(status.value());
        baseValueObject.setStatus(status.value());
        RequestAttributes requestAttributes = new ServletRequestAttributes(request);
        Map<String, Object> errorMap = this.errorAttributes.getErrorAttributes(requestAttributes, false);
        baseValueObject.setMessage(errorMap.get("error") + " - " + errorMap.get("message"));
        baseValueObject.setSuccess(false);
        return baseValueObject;
    }

    @Override
    public String getErrorPath() {
        return "/error";
    }

    private HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request
                .getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        try {
            return HttpStatus.valueOf(statusCode);
        } catch (Exception ex) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
    }


}

